package com.xiaoxu.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.xiaoxu.spzx.model.entity.user.UserInfo;
import com.xiaoxu.spzx.utils.AuthContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class UserLoginAuthInterceptor implements HandlerInterceptor {
//拦截前端所有以api开头的接口，只是把当前用户直接放到ThreadLocal中即可，没有别的业务
    @Autowired
    private RedisTemplate<String , String> redisTemplate ;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
//        //1.预检请求
//        String method = request.getMethod();
//        if ("OPTIONS".equalsIgnoreCase(method)){
//            return true;
//        }
        String token = request.getHeader("token");
//        if (StrUtil.isEmpty(token)){
//
//        }
        // 如果token不为空，那么此时验证token的合法性



        String userInfoJSON =
                redisTemplate.opsForValue()
                        .get("user:login"+token);
        //放到ThreadLocal中
        AuthContextUtil.setUserInfo(JSON.parseObject(userInfoJSON,UserInfo.class));
        return true ;
    }


    //响应208状态码给前端
//    private void responseNoLoginInfo(HttpServletResponse response) {
//        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
//        PrintWriter writer = null;
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("text/html; charset=utf-8");
//        try {
//            writer = response.getWriter();
//            writer.print(JSON.toJSONString(result));
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            if (writer != null) writer.close();
//        }
//    }
}
